<template>
    <div>
        <el-form :rules="rules" :model="formData" ref="titleForm" label-position="right" label-width="60px">
            <el-form-item label="标题" class="demo-form-inline" prop="title">
                <el-input placeholder="请输入标题" v-model="formData.title" style="margin-left: 10px;width:60%"></el-input>
            </el-form-item>
            <el-form-item label="标签" prop="dynamicTags">
                <el-tag
                        style="margin-left: 10px;"
                        :key="tag"
                        v-for="tag in formData.dynamicTags"
                        closable
                        :disable-transitions="false"
                        @close="handleClose(tag)">
                    {{tag}}
                </el-tag>
                <el-select v-model="value" filterable placeholder="请选择标签" :change="handleSelected()"
                           style="margin-left: 10px;">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <editor
                    ref="toastuiEditor"
                    :initialValue="editorText"
                    :options="editorOptions"
                    height="600px"
                    initialEditType="markdown"
                    previewStyle="vertical"
                    @load="onEditorLoad"
                    @focus="onEditorFocus"
                    @blur="onEditorBlur"
                    @change="onEditorChange"
                    @stateChange="onEditorStateChange"
            />
        </el-form>

    </div>

</template>

<script>
    // tui chart 插件
    import 'tui-chart/dist/tui-chart.css';
    import chart from '@toast-ui/editor-plugin-chart';

    // tui 颜色插件
    import colorSyntax from '@toast-ui/editor-plugin-color-syntax';
    import 'tui-color-picker/dist/tui-color-picker.css'

    // 合并单元格
    import tableMergedCell from '@toast-ui/editor-plugin-table-merged-cell';

    // uml 插件
    import uml from '@toast-ui/editor-plugin-uml';

    // 国际化
    import '@toast-ui/editor/dist/i18n/zh-cn';

    // tui editor
    import "codemirror/lib/codemirror.css";
    import "@toast-ui/editor/dist/toastui-editor.css";
    import {Editor} from "@toast-ui/vue-editor";

    // 代码高亮插件
    import codeSyntaxHightlight from '@toast-ui/editor-plugin-code-syntax-highlight';
    import hljs from 'highlight.js';
    import 'highlight.js/styles/github.css'

    import {mapActions} from 'vuex'

    // 图片上传地址
    const path = process.env.VUE_APP_BASE_API;

    // 导入sysTag API
    import {getSysTags} from "@/api/sys_tag";
    import {createKnowledge, queryKnowledgeByTitle} from "../../api/sys_knowledge";

    export default {
        data() {
            async function findTitle(rule, value, callback) {
                const res = await queryKnowledgeByTitle({title: value});
                if (res.code == 0) {
                    if (res.data == "记录不存在") {
                        callback()
                    } else {
                        callback("标题已存在，请修改")
                    }
                } else {
                    callback("查询异常")
                }
            }

            const checkTags = (rule, value, callback) => {
                if (value.length <= 0) {
                    callback("请选择标签")
                } else {
                    callback()
                }
            }

            return {
                editorText: this.$store.state.setting.markDown.trim(),
                path: path,
                formData: {
                    title: '',
                    dynamicTags: [],
                    tags: '',
                    status: '',
                    content: '',
                    id: '',
                    create_time: 0,
                },
                options: [],
                value: '',
                editorOptions: {
                    hideModeSwitch: false,
                    language: 'zh-CN',
                    usageStatistics: false,
                    plugins: [chart, colorSyntax, tableMergedCell, uml, [codeSyntaxHightlight, {hljs}]],
                    toolbarItems: [
                        'heading',
                        'bold',
                        'italic',
                        'strike',
                        'divider',
                        'hr',
                        'quote',
                        'divider',
                        'ul',
                        'ol',
                        'task',
                        'indent',
                        'outdent',
                        'divider',
                        'table',
                        'image',
                        'link',
                        'divider',
                        'code',
                        'codeblock',
                        'divider',
                        {
                            type: 'button',
                            options: {
                                el: this.createButton('last'),
                                name: 'fullscreen',
                                tooltip: '全屏',
                                event: 'fullscreen'
                            }
                        },
                        {
                            type: 'button',
                            options: {
                                el: this.createSaveButton('last'),
                                name: 'save',
                                tooltip: '发布',
                                event: 'save'
                            }
                        },
                        {
                            type: 'button',
                            options: {
                                el: this.createSaveTmpButton('last'),
                                name: 'saveTmp',
                                tooltip: '保存草稿',
                                event: 'saveTmp'
                            }
                        }
                    ]
                },
                rules: {
                    title: [
                        {required: true, message: "请输入标题", trigger: "blur"},
                        {validator: findTitle, trigger: "blur"}
                    ],
                    dynamicTags: [
                        {type: 'array', validator: checkTags, required: true, message: "请选择标签", trigger: "change"},
                    ]
                }
            };

        },
        components: {
            editor: Editor,
        },
        methods: {
            ...mapActions('asideDisplayIsTrue', 'asideDisplayIsFalse', 'saveMarkdown'),
            onEditorLoad() {
                // implement your code
            },
            onEditorFocus() {
                // implement your code
            },
            onEditorBlur() {
                // implement your code

                let content = this.$refs.toastuiEditor.editor.mdEditor.getValue()

                content = content.replace(/\s*/g, "")
                if (content.length <= 1) {
                    this.$message({
                        type: 'warning',
                        message: '请输入发布内容'
                    })
                }
            },
            onEditorChange() {
                this.$store.dispatch('setting/saveMarkdown', this.$refs.toastuiEditor.editor.mdEditor.getValue())
            },
            onEditorStateChange() {
                // implement your code
            }
            ,
            //全屏按钮
            createButton(className) {
                const button = document.createElement('button')
                button.className = className
                button.innerHTML = `<i class="el-icon-full-screen" style="color:#000000;font-weight: bolder"></i>`
                return button
            },
            // 发布按钮
            createSaveButton(className) {
                const button = document.createElement('button')
                button.className = className
                button.innerHTML = `<i class="el-icon-check" style="color:#000000;font-weight: bolder"></i>`
                return button
            },

            //保存草稿 按钮
            createSaveTmpButton(className) {
                const button = document.createElement('button')
                button.className = className
                button.innerHTML = `<i class="el-icon-takeaway-box" style="color:#000000;font-weight: bolder"></i>`
                return button
            },
            //添加全屏按钮事件
            fullScreenEvent() {
                const cm = this.$refs.toastuiEditor.editor.mdEditor.cm
                //设置按钮点击事件
                this.$refs.toastuiEditor.editor.eventManager.addEventType('fullscreen')
                this.$refs.toastuiEditor.editor.eventManager.listen('fullscreen', () => {
                    this.$refs.toastuiEditor.editor.previewStyle = 'vertical'
                    //保存点击状态
                    cm.setOption('fullScreen', !cm.getOption('fullScreen'))
                    let ui = document.querySelector('.tui-editor-defaultUI')
                    if (cm.getOption('fullScreen')) {
                        ui.classList.add('fullScreen')
                        this.$store.dispatch('setting/asideDisplayIsFalse')
                    } else {
                        ui.classList.remove('fullScreen')
                        this.$store.dispatch('setting/asideDisplayIsTrue')
                    }
                })
            },
            //保存markdown
            saveMarkdown() {
                //设置按钮点击事件
                this.$refs.toastuiEditor.editor.eventManager.addEventType('save')
                this.$refs.toastuiEditor.editor.eventManager.listen('save', async () => {
                    this.formData.content = this.$refs.toastuiEditor.editor.mdEditor.getValue()
                    this.formData.tags = this.formData.dynamicTags
                    this.formData.status = "发布"
                    let res = await createKnowledge(this.formData);
                    if (res.code == 0) {
                        this.$message({
                            type: "success",
                            message: "创建/更改成功"
                        })
                        this.$store.dispatch('setting/saveMarkdown', "")
                        this.$router.push("/layout/sysKnowledgeQuery")
                    }
                })
            },
            saveMarkdownTmp() {
                //设置保存草稿
                this.$refs.toastuiEditor.editor.eventManager.addEventType('saveTmp')
                this.$refs.toastuiEditor.editor.eventManager.listen('saveTmp', async () => {
                    this.formData.content = this.$refs.toastuiEditor.editor.mdEditor.getValue()
                    this.formData.tags = this.formData.dynamicTags
                    this.formData.status = "草稿"
                    let res = await createKnowledge(this.formData);
                    if (res.code == 0) {
                        this.$message({
                            type: "success",
                            message: "保存草稿成功"
                        })
                        this.$store.dispatch('setting/saveMarkdown', "")
                        this.$router.push("/layout/sysKnowledgeQuery")
                    }
                })
            },
            // 刷新事件
            beforeunloadHandler(e) {
                // 全屏左侧隐藏显示处理
                this.$store.dispatch('setting/asideDisplayIsTrue')
            },
            // 上传文件
            upload(file, callback) {
                const formData = new FormData()
                formData.append('file', file)
                const ajax = new XMLHttpRequest()
                ajax.open('POST', this.path + '/fileUploadAndDownload/upload', true)
                ajax.setRequestHeader('x-token', this.$store.state.user.token);
                ajax.send(formData)
                ajax.onreadystatechange = function () {
                    if (ajax.readyState === 4) {
                        if ((ajax.status >= 200 && ajax.status < 300) || ajax.status === 304) {
                            const obj = JSON.parse(ajax.responseText)
                            callback(obj.data.file.url)
                        }
                    }
                }
            },
            // 关闭标签时触发
            handleClose(tag) {
                this.formData.dynamicTags.splice(this.formData.dynamicTags.indexOf(tag), 1);
                this.$refs.titleForm.validateField('dynamicTags')
            },
            // 选择标签时触发
            handleSelected() {
                if (this.value) {
                    if (this.formData.dynamicTags.indexOf(this.value) > -1) {
                        this.$message({
                            type: 'warning',
                            message: '您选择的标签已存在，请重新选择'
                        })
                    } else {
                        this.formData.dynamicTags.push(this.value);
                    }
                    this.$refs.titleForm.validateField('dynamicTags')
                }
                this.value = '';
            },
            // 初始化标签数据
            async initSysTags() {
                const res = await getSysTags();
                if (res.code == 0) {
                    let this_ = this
                    res.data.list.forEach(function (element) {
                        this_.options.push({
                            value: element.tagName,
                            label: element.tagName
                        })
                    });
                } else {
                    console.log("查询异常")
                }
            }
        },
        computed: {},
        mounted() {

            // 初始化挂载 按钮事件
            this.saveMarkdown()
            this.saveMarkdownTmp()
            this.fullScreenEvent()
            window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
            // 添加图片上传监听事件
            this.$refs.toastuiEditor.editor.eventManager.removeEventHandler('addImageBlobHook')
            // 添加自定义监听事件
            this.$refs.toastuiEditor.editor.eventManager.listen('addImageBlobHook', (blob, callback) => {
                // 此处填写自己的上传逻辑，url为上传后的图片地址
                this.upload(blob, url => {
                    callback(url)
                })
            })
            this.initSysTags()
            if (this.$route.params.row != undefined) {
                this.formData.title = this.$route.params.row.title
                this.formData.dynamicTags = this.$route.params.row.tags
                this.formData.id = this.$route.params.row.id
                this.formData.create_time = this.$route.params.row.create_time
                this.formData.status = this.$route.params.row.status
            }

            if (this.$route.params.row != undefined) {
                this.rules.title.pop()
            }

        },
        beforeCreate() {
            if (this.$route.params.row != undefined) {
                this.$store.dispatch('setting/saveMarkdown', this.$route.params.row.content)
            } else {
                this.$store.dispatch('setting/saveMarkdown', "")
            }
        },
        created() {

        },
        watch: {},
        destroyed() {
            window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
        }
    };


</script>

<style lang="scss">
    // 事件按钮需要使用类所以不能加scoped
    .fullScreen {
        position: fixed !important;
        z-index: 999;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: #fff;
    }

    .tui-editor-defaultUI {
        border: none;
    }

    .el-tag + .el-tag {
        margin-left: 10px;
    }

    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }

    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }
</style>
